package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestHeader;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public Result<String> register(String username, String password) {
        password = Md5Util.getMD5String(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(username), User::getUsername, username);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            User user1 = new User();
            user1.setUsername(username);
            user1.setPassword(password);
            user1.setCreateTime(LocalDateTime.now());
            user1.setUpdateTime(LocalDateTime.now());
            this.save(user1);
            return Result.success("注册成功");
        }
        return Result.error("用户名已被占用");
    }

    @Override
    public Result login(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(username), User::getUsername, username);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(password).equals(user.getPassword())) {
            // 登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genToken(claims);

            stringRedisTemplate.opsForValue().set(token, token, 1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @Override
    public Result userInfo(HttpServletRequest request) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(username), User::getUsername, username);
        User user = this.getOne(queryWrapper);
        return Result.success(user);
    }

    @Override
    public Result updatePwd(Map<String, String> params, String token) {
        // 1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!org.springframework.util.StringUtils.hasLength(oldPwd) || !org.springframework.util.StringUtils.hasLength(newPwd) || !org.springframework.util.StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        // 原密码是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(username), User::getUsername, username);
        User user = this.getOne(queryWrapper);
        String password = user.getPassword();
        String md5StrPwd = Md5Util.getMD5String(oldPwd);
        if (!password.equals(md5StrPwd)) {
            return Result.error("原密码填写错误");
        }

        // 新密码和第二次密码是否一样
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次填写密码不一致");
        }
        // 2.调用service完成密码更新
        String md5StrNewPwd = Md5Util.getMD5String(newPwd);
        user.setPassword(md5StrNewPwd);
        this.updateById(user);

        // 删除redis中对应的token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success("修改密码成功");
    }

    @Override
    public Result updateAvatar(String avatarUrl, HttpServletRequest request) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user = new User();
        user.setId(id);
        user.setUserPic(avatarUrl);
        user.setUpdateTime(LocalDateTime.now());
        boolean b = this.updateById(user);
        String token = request.getHeader("Authorization");
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success(b);
    }
}
